import axios from 'axios'
import { message } from 'antd'
import store from '../store'
import { clearToken } from './token'
import { setUser } from '../store/modules/user'
import routes from '../router'
const http = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
}) 
http.interceptors.response.use(res => res.data, err =>{
 if(err.response.status === 401){
    message.error('token无效，请重新登录')
    clearToken()
    store.dispatch(setUser({}))
    routes.navigate('/login', { replace: true })
}
return Promise.reject(err)
})
http.interceptors.request.use(config =>{
const { login } = store.getState() 
 // 除了登录请求外，其他请求统一添加 token
 if (!config.url.startsWith('/authorizations')) {
    config.headers.Authorization = `Bearer ${login.token}`
  }
 return config
})
export default http